package com.android.lovely.api

import com.android.lovely.api.service.botService
import com.android.lovely.api.service.userService
import com.android.lovely.const.CardUL
import com.android.lovely.const.CollectRobot
import com.android.lovely.room.BotCacheService
import com.android.lovely.room.chat.database.LoadMoreMessage.cardId
import com.android.lovely.user.UserManager
import com.facebook.ProfileManager
import com.kotlin.extensions.bus.FlowBus
import com.kotlin.extensions.bus.post
import com.kotlin.extensions.coroutine.CoroutineExt.doOnIO
import com.kotlin.extensions.coroutine.CoroutineExt.doOnMain

suspend fun getBotDetailUseCase(id: Int) = botService.requestBotDetail(mapOf("bot_id" to id))

suspend fun getChatHistoryUseCase(id: Int, lastId: Int = Int.MAX_VALUE, size: Int = 10) =
    userService.getMessage(mapOf("bot_id" to id, "size" to size, "last_id" to lastId))

suspend fun queryNewMessageCount(id: Int, messageId: Int) =
    userService.queryNewMessageCount(mapOf("bot_id" to id, "chat_id" to messageId))["num"] ?: 0
suspend fun fetchBotCardsListCase(id: Int, page: Int, size: Int) =
    botService.getBotCards(mapOf("bot_id" to id, "page" to page, "size" to size))

//suspend fun getAdvertiseIdUseCase() = doOnIO { systemService.getAdmobId() }

/**
 * 激活所有内容
 */
suspend fun unlockAllCardUserCase(id: Int) = doOnIO { botService.unloadAll(mapOf("bot_id" to id)) }

//suspend fun getCurrentSign() = doOnIO { userService.getDailyList().checked }

/**
 * 内容激活用例，负责处理内容激活和相关更新
 */
object UnlockCardUseCase {
    suspend fun execute(botId: Int, contentId: Int) = doOnIO {

        runCatching {
            val surplus = UserManager.userInfo?.point ?: 0

            val purchaseParams = mapOf("card_id" to contentId)
            val response = botService.buyCard(purchaseParams).data
            if (response != null) {
                val gems = response.getOrDefault("surplus", surplus)
                doOnMain {
                    UserManager.updateGems(gems)
                }
            }
            updateContentAndNotify(botId, contentId)
        }.onFailure {
            if (it is LovelyException && it.message?.contains("already buy") == true) {
                updateContentAndNotify(botId, contentId)
            } else {
                throw it
            }
        }

    }

    private suspend fun updateContentAndNotify(botId: Int, contentId: Int) {
        BotCacheService.updateBot(botId) {
            cards.find { it.id == contentId }?.isUnlock = true
        }
        FlowBus.post(CardUL(listOf(contentId)))
    }
}

suspend fun updateBackgroundUseCase(cardId: Int, botId: Int) {
    botService.updateChatBg(mapOf("bot_id" to botId, "card_id" to cardId))
}

suspend fun collectRobotUseCase(id: Int) = userService.collect(mapOf("bot_id" to id)).apply {
    FlowBus.post(CollectRobot(id))
}

suspend fun getRewardGemUseCase(type: String) =
    doOnIO { userService.getReward(mapOf("ad_type" to type)) }

suspend fun hasNewSysMessageUseCase() =
    doOnIO { userService.hasNewSysMessage().getOrDefault("unread_num", 0) > 0 }